﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using wUniAppPCL.IO;

namespace wUniApp.WPF.Data
{
  public enum wFileLocation {  FullPath, AppDirectory };

  public class wFileStorage : wBaseStorage
  {
    public wFileStorage(wFileLocation fLoc = wFileLocation.FullPath)
    {
      LocationMode = fLoc;
    }

    private string GetFullFileName(string fileName)
    {
      return (LocationMode == wFileLocation.FullPath) ? fileName : Path.Combine(AppDirectory, fileName);
    }


    public wFileLocation LocationMode { get; set; }

    public string AppDirectory
    {
      get
      {
        return Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
      }
    }

    public override Stream Read(string name, bool onlyRead)
    {
      string fileName = GetFullFileName(name);
      if (onlyRead)
      {
        return File.Open(fileName, FileMode.Open, FileAccess.Read);
      }
      else
      {
        if (Exist(fileName)) Delete(fileName);
        return File.Open(fileName, FileMode.Create, FileAccess.ReadWrite);
      }
    }

    public override bool Exist(string name)
    {
      string fileName = GetFullFileName(name);
      return File.Exists(fileName);
    }

    public override void Write(Stream stream, string name)
    {
      string fileName = GetFullFileName(name);
      using (var fs = File.Create(name))
      {
        stream.CopyTo(fs);
      }
    }

    public override void Delete(string name)
    {
      string fileName = GetFullFileName(name);
      File.Delete(name);
    }
  }
}
